import type { Module, ActionContext } from 'vuex'
import type { AxiosResponse } from 'axios'
import type { SystemDictStateType } from './typings'
import {
  getSystemDictList,
  getSystemDictTree,
  postSystemDictSubmit,
  postSystemDictRemove
} from '~/api/system/systemDict'
import { filterValueEnum } from '~/utils/util'

const systemDict: Module<SystemDictStateType, SystemDictStateType> = {
  namespaced: true,
  state: {
    parentDictSelectList: [], // 上级字典 下拉选项
    parentDictEnum: {} // 上级字典 枚举
  },
  getters: {
    parentDictSelectList: (state) => state.parentDictSelectList,
    parentDictEnum: (state) => state.parentDictEnum
  },
  mutations: {
    SET_PARENTDICTSELECTLIST: (state, payload) => {
      state.parentDictSelectList = payload
      state.parentDictEnum = filterValueEnum(
        payload,
        'key',
        'title'
      ) as SystemDictStateType['parentDictEnum']
    }
  },
  actions: {
    // 获取 字典管理 列表
    GetSystemDictList<S, T>(_: ActionContext<S, T>, params: T) {
      return new Promise((resolve, reject) => {
        getSystemDictList<T>(params)
          .then((res: AxiosResponse) => {
            resolve(res.data)
          })
          .catch((err: AxiosResponse) => {
            reject(err)
          })
      })
    },

    // 获取 上级字典
    GetSystemDictTree<S, T>({ commit }: ActionContext<S, T>, params: T) {
      return new Promise((resolve, reject) => {
        getSystemDictTree<T>(params)
          .then((res: AxiosResponse) => {
            commit(
              'SET_PARENTDICTSELECTLIST',
              res?.data?.data?.concat([{ key: '0', title: '顶级' }]) || []
            )
            resolve(res.data)
          })
          .catch((err: AxiosResponse) => {
            reject(err)
          })
      })
    },

    // 字典管理 新增
    PostSystemDictSubmit<S, T>(_: ActionContext<S, T>, params: T) {
      return new Promise((resolve, reject) => {
        postSystemDictSubmit<T>(params)
          .then((res: AxiosResponse) => {
            resolve(res.data)
          })
          .catch((err: AxiosResponse) => {
            reject(err)
          })
      })
    },

    // 删除字典
    PostSystemDictRemove<S, T>(_: ActionContext<S, T>, params: T) {
      return new Promise((resolve, reject) => {
        postSystemDictRemove<T>(params)
          .then((res: AxiosResponse) => {
            resolve(res.data)
          })
          .catch((err: AxiosResponse) => {
            reject(err)
          })
      })
    }
  }
}

export default systemDict
